package com.example.controller;

import com.example.service.ResourceConsumerService;
import com.example.service.SafetyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.lang.management.OperatingSystemMXBean;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api")
public class ResourceController {

    @Autowired
    private ResourceConsumerService resourceConsumerService;
    
    @Autowired
    private SafetyService safetyService;

    @GetMapping("/status")
    public Map<String, Object> getStatus() {
        Map<String, Object> status = new HashMap<>();
        
        // 获取系统信息
        OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean();
        MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean();
        
        status.put("service_status", resourceConsumerService.getStatus());
        status.put("safety_status", safetyService.getSafetyStatus());
        status.put("available_processors", osBean.getAvailableProcessors());
        status.put("system_load_average", osBean.getSystemLoadAverage());
        
        // 内存信息
        long usedMemory = memoryBean.getHeapMemoryUsage().getUsed();
        long maxMemory = memoryBean.getHeapMemoryUsage().getMax();
        status.put("heap_memory_used_mb", usedMemory / (1024 * 1024));
        status.put("heap_memory_max_mb", maxMemory / (1024 * 1024));
        status.put("heap_memory_usage_percent", (usedMemory * 100) / maxMemory);
        
        return status;
    }

    @GetMapping("/health")
    public Map<String, String> health() {
        Map<String, String> health = new HashMap<>();
        health.put("status", "UP");
        health.put("message", "资源消耗应用正在运行");
        return health;
    }

    @GetMapping("/")
    public String home() {
        return "资源消耗应用正在运行！<br><br>" +
               "监控接口：<br>" +
               "<a href='/api/status'>/api/status</a> - 查看详细状态<br>" +
               "<a href='/api/health'>/api/health</a> - 健康检查<br>" +
               "<a href='/actuator/health'>/actuator/health</a> - Spring Boot 健康检查<br>" +
               "<a href='/actuator/metrics'>/actuator/metrics</a> - 应用指标";
    }
} 